import { Colony } from '@/bot/Colony';
import { NormalColony } from '../NormalColony';

type CreepHandler = (creep: Creep) => any;

export class BaseColonyModule {

    readonly colony: NormalColony;
    readonly name: string;

    constructor(colony: Colony, name: string) {
        // 弹性检查
        if (colony.operatingMode === 'normal') {
            this.colony = <NormalColony>colony;
            this.name = name;
        }
        else {
            throw new Error('无法使用 operatingMode 非 normal 的 Colony 对象初始化该模块')
        }
    }

    get memory() {
        return this.colony.memory;
    }

    protected runCreeps(role: CreepRole, handler: CreepHandler, opts?: { disableAuto: boolean }) {
        this.colony.getCreepsByRole(role).forEach(creep => {
            // 任务分配
            if (creep.isIdle()) {
                handler(creep);
            }
            // 出生标志处理
            if (creep.memory.onBorn) {
                delete creep.memory.onBorn;
            }
            // 执行任务
            if (!opts.disableAuto) {
                creep.runTask();
            }
            // 自动接班
            if (
                creep.ticksToLive <= creep.body.length * CREEP_SPAWN_TIME
                && !creep.memory.temporary
                && !creep.memory.hasRequestedSuccessor
            ) {
                this.colony.spawnModule.recreateCreep(creep);
                creep.memory.hasRequestedSuccessor = true;
            }
        });
    }

}